<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>微信功能示例</title>
    <!-- 引入微信JS-SDK -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

    <!-- 引入腾讯地图SDK -->
    <script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        #map-container {
            width: 100%;
            height: 400px;
            margin: 20px 0;
            border: 1px solid #ddd;
        }
        .share-btn {
            padding: 12px 24px;
            margin: 10px;
            background: #1AAD19;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>微信功能演示</h1>
    
    <!-- 地图容器 -->
    <div id="map-container"></div>

    <!-- 分享按钮 -->
    <button class="share-btn" onclick="shareToTimeline()">分享到朋友圈</button>
    <button class="share-btn" onclick="shareToFriend()">分享给朋友</button>
    <button class="share-btn" onclick="searchAddress()">搜索</button>
    <button class="share-btn" onclick="initMapWithH5Location()">获取位置</button>

    <!-- 输入框 -->
    <input type="text" id="address" placeholder="请输入地址">
    <button class="share-btn" onclick="searchAddress()">搜索</button>

    <script>
        // 微信配置参数（需从后端获取）
        let wxConfig = null;
        let map = null;
        // 从url获取参数
        const urlParams = new URLSearchParams(window.location.search);
        const token = urlParams.get('token');


        function searchAddress() {
            const address = document.getElementById("address").value;
            const url = `https://apis.map.qq.com/ws/place/v1/search?key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74&keyword=${address}&boundary=region(北京,1)&page_size=20&page_index=1`;
            fetch("https://www.api.nl9555.com/index/proxyForwarding", { method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                    "token": token || JSON.parse(localStorage.getItem("token")).data,
                },
                body: JSON.stringify({ 
                    url: url
                })
            })
            .then(res => res.json())
            .then(res => {
                console.log(res);
                const obj =  JSON.parse(res.body);
                console.log("obj", obj)
                const data = obj.data;
                const pois = data.pois;
                const poi = pois[0];
                const lat = poi.lat;
                const lng = poi.lng;
                const address = poi.address;
            });
        }
      

        // 初始化微信配置
        function initWxConfig() {
            fetch("https://www.api.nl9555.com/weChat/JSSDK", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "token": token || JSON.parse(localStorage.getItem("token")).data,
                },
                body: JSON.stringify({ url: window.location.href.split('#')[0] })
            })
            .then(res => res.json())
            .then(res => {
                wxConfig = res.data;
                wx.config({
                    debug: false,
                    appId: wxConfig.appId,
                    timestamp: wxConfig.timestamp,
                    nonceStr: wxConfig.nonceStr,
                    signature: wxConfig.signature,
                    jsApiList: ["chooseWXPay", "openLocation", "getLocation", "updateAppMessageShareData", "updateTimelineShareData"]
                });

                wx.ready(() => {
                    console.log("微信JS-SDK初始化成功");
                    initMap();
                    wx.hideOptionMenu(); // 隐藏默认菜单
                });

                wx.error(err => {
                    console.error("微信初始化失败:", err);
                    initMapWithH5Location();
                });
            })
            .catch(err => {
                console.error("获取配置失败:", err);
                initMapWithH5Location();
            });
        }

        // 初始化地图
        function initMap() {
            map = new TMap.Map("map-container", {
                center: new TMap.LatLng(39.9088, 116.3975), // 初始中心点（北京）
                zoom: 13
            });

            // 添加点击事件获取坐标
            map.on("click", async (e) => {
                const lat = e.latLng.getLat();
                const lng = e.latLng.getLng();
                console.log("地图坐标：", lat, lng);
                alert(`经度：${lng}\n纬度：${lat}`);
                const addressInfo = await getAddressInfo(lat, lng);
                console.log(addressInfo);
            });
        }

        // H5定位回退方案
        function initMapWithH5Location() {
            // if (navigator.geolocation) {
            //     navigator.geolocation.getCurrentPosition(
            //         async (position) => {
            //             const lat = position.coords.latitude;
            //             const lng = position.coords.longitude;
            //             console.log("H5定位坐标：", lat, lng);
            //             alert(`H5定位成功\n经度：${lng}\n纬度：${lat}`);
            //             const addressInfo = await getAddressInfo(lat, lng);
            //             console.log(addressInfo);
            //         },
            //         (error) => {
            //             console.error("获取位置失败:", error);
            //             alert("获取位置失败，请检查定位权限");
            //         }
            //     );
            // } else {
            //     alert("浏览器不支持地理定位");
            // }
            
            const url = "https://apis.map.qq.com/ws/location/v1/ip?key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74";
            fetch("https://www.api.nl9555.com/index/proxyForwarding", { method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                    "token": token || JSON.parse(localStorage.getItem("token")).data,
                },
                body: JSON.stringify({ 
                    url: url
                })
            })
            .then(res => res.json())
            .then(res => {
                console.log(res);
            });
        }


        // 获取地址信息（改为 fetch 请求）
        async function getAddressInfo(lat, lng) {
            const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74&get_poi=1`;
            const response = await fetch(url, { method: 'GET' });
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const data = await response.json();
            if (data.status !== 0) {
                throw new Error(data.message || '解析失败');
            }
            const result = data.result;
            return `
                📍 精确地址：${result.address}<br>
                🗺️ 推荐地址：${result.formatted_addresses.recommend}<br>
                🏠 周边POI：<br>
                ${result.pois.map(poi => `• ${poi.title}`).join('\n')}
            `;
        }

        // 自定义分享功能
        function shareToTimeline() {
            wx.updateTimelineShareData({
                title: "自定义朋友圈标题",
                link: window.location.href,
                imgUrl: "https://www.h5.nl9555.com/share.png",
                success: () => {
                    alert("朋友圈分享成功");
                }
            });
        }

        function shareToFriend() {
            wx.updateAppMessageShareData({
                title: "自定义分享标题",
                desc: "自定义分享描述",
                link: window.location.href,
                imgUrl: "https://www.h5.nl9555.com/share.png",
                success: () => {
                    alert("分享给朋友成功");
                }
            });
        }

        // 页面加载时初始化
        document.addEventListener("DOMContentLoaded", () => {
            initWxConfig();
        });
    </script>
</body>
</html>